<template>
  <div class="college-manage-container">
    <a-card class="layout-card">
      <a-row align="middle" justify="space-between">
        <SearchGroup
          :label-option="labelOption"
          @handleSearch="loadData(1)"
          @handleReset="reset"
          :searchOption="filterOption"
        />
        <a-col>
          <a-button
            class="btn"
            type="primary"
            v-if="route.meta?.buttonList?.includes('CollegeManageAdd')"
            @click="Data.addVisible = true"
          >
            <plus-outlined />新建
          </a-button>
          <a-button
            class="btn"
            v-if="route.meta?.buttonList?.includes('CollegeManageManyDelete')"
            type="primary"
            danger
            @click="handleDel"
          >
            删除所选学院
          </a-button>
          <a-upload
            :showUploadList="Data.showUploadList"
            accept=".xlsx, .xls, .dbf"
            name="file"
            :customRequest="customRequest"
          >
            <a-button
              class="btn"
              v-if="route.meta?.buttonList?.includes('CollegeManageImportList')"
              type="primary"
            >
              导入学院
            </a-button>
          </a-upload>
        </a-col>
      </a-row>
      <a-table
        :row-selection="{ selectedRowKeys: Data.selectedRowKeys, onChange: onSelectChange }"
        class="tablstyle"
        rowKey="xydm"
        :scroll="{ x: 1450 }"
        bordered
        :loading="loading"
        :pagination="false"
        :dataSource="list"
        :columns="columns"
        :row-class-name="
          (record, index) => {
            if (!record?.statistics?.spCount) return 'bg-red-200'
            if (
              Number(record?.statistics?.overCount || 0) /
                Number(record?.statistics?.kmCount || 1) <
              1
            )
              return 'bg-orange-200'
            return 'bg-green-200'
          }
        "
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex == 'index'">
            {{ (curPage - 1) * pageSize + (index + 1) }}
          </template>

          <template v-if="column.dataIndex === 'overCount'">
            <div class="pr-5">
              <a-progress
                :percent="
                  (Number(record?.statistics?.overCount || 0) /
                    Number(record?.statistics?.kmCount || 1)) *
                  100
                "
                :format="percent => `${percent.toFixed(2)}%`"
              />
            </div>
            <span>
              <i class="text-red-600"> {{ record?.statistics?.overCount || 0 }} </i> /
              {{ record?.statistics?.kmCount || 0 }}
            </span>
          </template>
          <template v-if="column.dataIndex == 'operation'">
            <a-button
              type="link"
              v-if="route.meta?.buttonList?.includes('CollegeManageAssignTeacher')"
              @click="showAllotModal(record)"
            >
              分配管理员
            </a-button>
          </template>
        </template>
      </a-table>
      <a-pagination
        class="pagination"
        :show-total="total => `共 ${total} 条`"
        :show-size-changer="false"
        show-quick-jumper
        v-model:current="curPage"
        v-model:pageSize="pageSize"
        :total="total"
      />
      <addCollege
        v-if="Data.addVisible"
        :visible="Data.addVisible"
        @refresh="loadData"
        @cancel="Data.addVisible = false"
        :addForm="Data.addForm"
      />
      <!-- 分配教师 -->
      <a-modal
        width="30%"
        :visible="Data.allotVisible"
        @cancel="cancelAllotModal"
        @ok="handleAllot"
        title="学院管理员分配"
      >
        <div class="allot-modal">
          <div class="allotTitle">分配学院:{{ Data.curCollege.xymc }}</div>
          <a-form-item label="学院管理员">
            <a-select
              v-model:value="Data.userId"
              show-search
              allowClear
              placeholder="请选择教务（可按工号或姓名搜索）"
              :default-active-first-option="false"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="null"
              :options="Data.teacherOptions"
              :field-names="{ label: 'jsxm', value: 'account' }"
            />
          </a-form-item>
        </div>
      </a-modal>
    </a-card>
  </div>
</template>
<script lang="ts" setup>
import { h, onMounted, ref, reactive } from 'vue'
import {
  deleteCollegeById,
  getCollegeList,
  saveDistributeXyAccount,
  getXyAccountArr,
  saveCancelXyXyAccount,
  getXyKmPyJdArr,
} from '/@/api/organization/collegeManage'
import addCollege from './addCollege.vue'
import { useList } from '/@/hooks/web/useList'
import { useMessage } from '/@/hooks/web/useMessage'
import { uploadApi } from '/@/api/sys/upload'
const { createConfirm, createMessage } = useMessage()
const columns = ref([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    width: 80,
    fixed: true,
  },
  {
    title: '学院代码',
    dataIndex: 'xydm',
    key: 'xydm',
    align: 'center',
  },
  {
    title: '学院名称',
    dataIndex: 'xymc',
    key: 'xymc',
    align: 'center',
  },
  {
    title: '录入试卷科目',
    dataIndex: 'lrsjCount',
    key: 'lrsjCount',
    align: 'center',
    width: 120,
    customRender: ({ record }) => {
      if (!record?.statistics?.lrsjCount) return 0
      return record?.statistics?.lrsjCount
    },
  },
  {
    title: '试评科目数',
    dataIndex: 'spCount',
    key: 'spCount',
    align: 'center',
    width: 120,
    customRender: ({ record, value }) => {
      if (!record?.statistics?.spCount) return 0
      return record?.statistics?.spCount
    },
  },
  {
    title: '正评科目数',
    dataIndex: 'zpCount',
    key: 'zpCount',
    align: 'center',
    width: 120,
    customRender: ({ record, value }) => {
      if (!record?.statistics?.zpCount) return 0
      return record?.statistics?.zpCount
    },
  },
  {
    title: '评阅完成科目',
    dataIndex: 'overCount',
    key: 'overCount',
    align: 'center',
    width: 240,
  },
  {
    title: '学院管理员',
    dataIndex: 'jsxm',
    key: 'jsxm',
    customRender: ({ record, value }) => {
      if (!value) return '--'
      return `(${value})${record.account}`
    },
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    width: 300,
    fixed: 'right',
  },
])

const Data = reactive({
  userId: '',
  curCollege: {},
  teacherOptions: [],
  addForm: {
    xydm: '',
    xymc: '',
  },
  addVisible: false,
  selectedRowKeys: [],
  showUploadList: false,
  allotVisible: false,
} as any)

import { useRoute } from 'vue-router'
const route = useRoute()

const labelOption = ref([{ name: '学院代码', key: 'xydm' }])

const { reset, loadData, filterOption, curPage, total, pageSize, list, loading } = useList(
  getCollegeList,
  {
    requestSuccess() {
      getKmApplyOverview()
    },
  }
)

function getKmApplyOverview() {
  if (list.value?.length == 0) return
  let todoList = list.value.map(item => item.xydm) || []
  getXyKmPyJdArr({
    todoList,
  }).then(res => {
    if (res.code == 200 && list.value?.length)
      for (let i = 0; i < list.value.length; i++) {
        list.value[i].statistics = {}
        for (let j = 0; j < res.data.length; j++) {
          if (list.value[i].xydm == res.data[j].xydm) {
            list.value[i].statistics = res.data[j]
            break
          }
        }
      }
  })
}

const onSelectChange = keys => {
  Data.selectedRowKeys = keys
}

const handleDel = () => {
  if (!Data.selectedRowKeys.length) {
    return createMessage.warning('您还没有选择学院！')
  }
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () => h('span', '您确定删除所选学院吗？'),
    onOk: async () => {
      const { code, message } = await deleteCollegeById({
        xydmList: Data.selectedRowKeys,
      })
      if (code === 200) {
        createMessage.success('删除成功！')
        Data.selectedRowKeys = []
        loadData()
        return
      }
      createMessage.error(message)
    },
  })
}

// 打开分配教师弹窗
const showAllotModal = row => {
  Data.curCollege = row
  if (row.account) {
    Data.userId = row.account
  }
  Data.allotVisible = true
}

// 关闭分配教师弹窗
const cancelAllotModal = () => {
  Data.allotVisible = false
  Data.userId = undefined
  Data.curCollege = {}
}

// 教师列表
const getTeacherOptions = async () => {
  const { data } = await getXyAccountArr({
    pageSize: 0,
  })
  Data.teacherOptions = data?.filter(item => (item.jsxm = `(${item.jsxm})${item.account}`))
}

// 提交分配学院管理员
const handleAllot = async () => {
  if (Data.curCollege.account && Data.curCollege.account !== Data.userId) {
    const { code, message } = await saveCancelXyXyAccount({
      account: Data.curCollege.account, //负责教师id
      manageXydm: Data.curCollege.xydm, //学院代码
    })
    if (code !== 200) {
      createMessage.error(message)
    }
  }
  if (!Data.userId) {
    loadData()
    cancelAllotModal()
    return
  }
  const { code, message } = await saveDistributeXyAccount({
    account: Data.userId, //负责教师id
    manageXydm: Data.curCollege.xydm, //学院代码
  })
  if (code === 200) {
    loadData()
    cancelAllotModal()
    createMessage.success('分配成功')
  } else {
    createMessage.error(message)
  }
}

onMounted(() => {
  getTeacherOptions()
})

// 学院管理
const customRequest = async file => {
  const fileNames = file.file.name.split('.')
  const fileType = fileNames[fileNames.length - 1].toLocaleLowerCase()
  if (fileType != 'dbf' && fileType != 'xlsx' && fileType != 'xls') {
    createMessage.warning('只能上传.xlsx、.xls或.dbf类型的文件！')
    Data.showUploadList = false
    return
  }
  const {
    data: { code, message },
  }: any = await uploadApi(`/importExport/xyImport`, file)
  if (code === 200) {
    createMessage.success('上传文件成功')
    loadData()
  } else {
    createMessage.error(message)
  }
  Data.showUploadList = false
}

// 模板下载

function downloadTemplate() {
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () => h('span', '你正在操作下载导入模板，请注意保存！'),
    okText: '立即下载',
    cancelText: '取消下载',
    onOk: async () => {
      // TODO 下载模板
    },
  })
}
</script>
<style lang="less" scoped>
.college-manage-container {
  // height: @c_height;
}
.layout-card {
  border-radius: 8px;
}
.tablstyle {
  padding: 15px 0;
}

.btn {
  margin-left: 10px;
}
.allot-modal {
  padding: 0 20px;
}
.allotTitle {
  padding: 20px 0;
  font-size: 16px;
  font-weight: 700;
}
</style>
<style lang="less">
.teacher-info {
  .ant-pagination {
    margin-top: 20px;
  }
}
</style>
